from django.shortcuts import render, get_object_or_404
from .models import Post, Category
from comments.forms import CommontForm
import markdown


def index(request):
    post_list = Post.objects.all()
    # 所有文章markdown渲染
    for post in post_list:
        post.body = markdown.markdown(post.body, extensions=['markdown.extensions.extra',
                                                             'markdown.extensions.codehilite',
                                                             'markdown.extensions.toc'])
    return render(request, 'blog/index.html', {'post_list': post_list})


def detail(request, pk):
    post = get_object_or_404(Post, pk=pk)
    # 将文章主题用markdown包进行渲染，并使用以下扩展
    post.body = markdown.markdown(post.body, extensions=['markdown.extensions.extra',
                                                         'markdown.extensions.codehilite',
                                                         'markdown.extensions.toc'])
    comment_list = post.comment_set.all()
    form = CommontForm()
    return render(request, 'blog/detail.html', {'post': post,
                                                'form': form,
                                                'comment_list': comment_list})


def archives(request, year, month):
    # 根据日期筛选文章列表
    post_list = Post.objects.filter(created_time__year=year,
                                    created_time__month=month)
    return render(request, 'blog/archives.html', {'year': year,
                                                  'month': month,
                                                  'post_list': post_list})


def category(request, pk):
    # 根据筛选文章列表
    post_list = None
    cate = get_object_or_404(Category, pk=pk)
    if cate is not None:
        post_list = Post.objects.filter(category_id=pk)
    return render(request, 'blog/category.html', {'category': cate,
                                                  'post_list': post_list})
